package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);

        //判断【后端】用户是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) { // 用户已登录
            BaseContext.setCurrentId(empId);
            return true;
        }

        //判断【手机端】用户是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {// 用户已登录
            BaseContext.setCurrentId(userId);
            return true;
        }

        // 用户名未登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
